var interid=getQueryString("id");
setTimeout(function(){
	$("#name").rules("add",{
		remote: {
			url: 'qz/inters/checkName',
			data:{
				interName:function(){return $("#name").val();},
				interId:interid
            },
			type: "get",
			dataType: "json", 
			dataFilter:function(data,type){
				return data=="true"?false:true;
			}
		}, 
		messages: {remote: "该接口已添加"}
	});
} , parseInt(Math.random() * 1000));

var app = angular.module('interApp', []);

app.controller('interController', function($scope, $http, $q) {
	var bankMap={};
	var sp_map={};
	$scope.view=function(){
		$http.get(timestamp('qz/inters/get/'+getQueryString("id"))).success(function(response){
			$scope.inter=response.data;
			selectedDrawing("interfaceType","请选择接口类型");
			selectedDrawing("enableStatus","请选择接口部署状态");
			selectedDrawing("runStatus","请选择接口运行状态");
			

			$http.get(timestamp('qz/channel/getAll?status=2')).success(function(response){
				$scope.channelList=response.data;
				selectedDrawing("channelId","请选择支付渠道");
				$("#channelId").change(function(){  
					$("#businessId").select2("val", "");
					var channelId=$("#channelId").val();
					var url=channelId.length>0?'qz/business/getByChannelId/'+channelId:'qz/business/getAll/';
					$http.get(url).success(function(response){
						$scope.businessList=response.data;
					});
				});
	        });
				
			$http.get(timestamp('qz/business/getAll')).success(function(response){
				$scope.businessList=response.data;
				selectedDrawing("businessId","请选择业务类型");
	        });
				
			$http.get(timestamp('sys/dic/getByGroup/jym')).success(function(response){
				$scope.channelTypeList=response.data;
				selectedDrawing("channelType","请选择业务细类");
	        });
				
			$http.get(timestamp('sys/dic/getByGroup/txxy')).success(function(response){
				$scope.protocolList=response.data;
				selectedDrawing("protocol","请选择通信协议");
	        });
				
			$http.get(timestamp('sys/dic/getByGroup/bwgs')).success(function(response){
				$scope.packetFormatList=response.data;
				selectedDrawing("packetFormat","请选择报文格式");
	        });
				
			$http.get(timestamp('sys/dic/getByGroup/jhfs')).success(function(response){
				$scope.idnteractiveList=response.data;
				selectedDrawing("idnteractive","请选择交互方式");
	        });
	        
	    //attachment			 
			$http.get(timestamp('qz/inters/getAttchs/' + interid)).success(function(response){
				$scope.attachmentList=response.data;
      });
			
			var promises = [];
			var deferred = $q.defer();
			$http.get(timestamp('qz/inters/getSpMap/'+$scope.inter.channelInterId)).success(function(response){
				deferred.resolve(response.data);	
            });
			promises.push(deferred.promise);
			
			var deferred2 = $q.defer();
			$http.get(timestamp('sys/dic/getByGroup/yhqd')).success(function(response){
				deferred2.resolve(response.data);
	        });
			
			promises.push(deferred2.promise);
			
			var deferred3 = $q.defer();
			$http.get(timestamp('sys/dic/getByGroup/zfklx')).success(function(response){
				deferred3.resolve(response.data);
				
	        });
			promises.push(deferred3.promise);
			
			var deferred4 = $q.defer();
			$http.get(timestamp('sys/dic/getByGroup/zfksx')).success(function(response){
				deferred4.resolve(response.data);
	        });
			promises.push(deferred4.promise);
			
			$q.all(promises).then(function(datas){
				//---deferred start---
				$scope.inter_sp={bankids:[]};
				
				//转换支持银行为map对象
				var bkMap={};
				$.each(datas[0].spBankList,function(i,spbank){
					bkMap[spbank.localCode]=spbank.channelCode;
					bkMap[spbank.chaIntBankId]=spbank.localCode;
					//执行选中
					$scope.inter_sp.bankids[i]=spbank.localCode;
					//银行渠道代码页面赋值
					executeTimeout(function(){
						$("#"+spbank.localCode+"_bcode").val(spbank.channelCode);
					});
				});
				//---deferred2 start---
				//渲染支持银行列表selected插件
				selectedDrawing("bankids","请选择支持银行",false);
				
				//转换银行列表为map，并为已选择银行添加属性sel:true，用于默认选中
				$.each(datas[1],function(i,bank){
					bankMap[bank.dictionaryId]=bank;
					if(bkMap[bank.dictionaryId]!=null){
						datas[1][i].sel=true;
					}
				});
				$scope.bankList=datas[1];
				$scope.bankMap=bankMap;
				
				//增加change事件
				$("#bankids").change(function(){  
					$('.alert-danger').addClass("display-none");
					/**if($scope.inter_sp.bankids.length>0){
						$('.alert-danger').addClass("display-none");
					}else{
						$('.alert-danger p').html("请选择支持的银行");
					}**/
					for(var key in sp_map){
	       				 if(!$scope.inter_sp.bankids.contains(key)){
	       					 delete sp_map[key];
	       				 }
	       			}
				});
				
				//---deferred3 start---
				$scope.zfklxList=datas[2];
				
				//---deferred4 start---
				$scope.zfksxList=datas[3]; 
				
				executeTimeout(function(){
					var zfksxMap={};
					$.each(datas[0].spCardList,function(j,spcard){
    					$("#"+bkMap[spcard.spbankId]+"_"+spcard.localCode+"_zfklx").val(spcard.channelCode);
    					zfksxMap[spcard.chaIntCardId]={bankCode:bkMap[spcard.spbankId],cardCode:spcard.localCode}
					});
					
					$.each(datas[0].bcpList,function(j,bcp){
						var obj=zfksxMap[bcp.spcardId];
						var idStr=obj.bankCode+"-"+obj.cardCode+"-"+bcp.propertyId;
						$scope.selZfksx(idStr);
						$("#"+idStr).attr("checked","checked");
					});
				});
				
				var textStr="";
				$.each(datas[0].deployList,function(j,deploy){
					textStr+=deploy.type+","+deploy.ip+","+deploy.ports+","+deploy.url+","+deploy.response+","+deploy.deploy;
					if(j<datas[0].deployList.length-1){
						textStr+="\n";
					}
				});
				$scope.deployInfo=textStr;
			});
		});
				
	}
	
	$scope.refreshData=function(){
		$scope.view();
	}
	
	$scope.selZfksx=function(idStr){
		var ids=idStr.split("-");
		if(ids.length==3){
			var bankid=ids[0];
			var zfklx=ids[1];
			var zfksx=ids[2];
			if(sp_map[bankid] == undefined){
				sp_map[bankid]={};
			}
			if(sp_map[bankid][zfklx] == undefined){
				sp_map[bankid][zfklx]={};
			}
			if(sp_map[bankid][zfklx][zfksx] == undefined){
				sp_map[bankid][zfklx][zfksx]=0;
			}else{
				delete sp_map[bankid][zfklx][zfksx];
			}
			if(Object.keys(sp_map[bankid][zfklx]).length==0){
				$("#icon_"+bankid+"_"+zfklx).removeClass("fa fa-check-circle");
				delete sp_map[bankid][zfklx];
			}else{
				$("#icon_"+bankid+"_"+zfklx).addClass("fa fa-check-circle");
			}
			$('.alert-danger').addClass("display-none");
		}
	}
	
	$scope.initFormWizard=function(){
		if (!jQuery().bootstrapWizard) {
            return;
        }
        
		function forward(tab, navigation, index){
		   $('.alert-danger').addClass("display-none");
		   var total = navigation.find('li').length;
   		   var current = index + 1;
//   		   $('.stepHeader', $('#formWizard')).text('Step ' + (index + 1) + ' of ' + total);
   		   jQuery('li', $('#formWizard')).removeClass("done");
   		   var li_list = navigation.find('li');
   		   for (var i = 0; i < index; i++) {
   			   jQuery(li_list[i]).addClass("done");
   		   }
   		   if (current == 1) {
   			   $('#formWizard').find('.prevBtn').hide();
   		   } else {
   			   $('#formWizard').find('.prevBtn').show();
   		   }
   		   if (current >= total) {
                $('#formWizard').find('.nextBtn').hide();
                $('#formWizard').find('.submitBtn').show();
   		   } else {
                $('#formWizard').find('.nextBtn').show();
                $('#formWizard').find('.submitBtn').hide();
   		   }
		}
		
        /*-----------------------------------------------------------------------------------*/
		/*	Initialize Bootstrap Wizard
		/*-----------------------------------------------------------------------------------*/
        $('#formWizard').bootstrapWizard({
            'nextSelector': '.nextBtn',
            'previousSelector': '.prevBtn',
             onNext: function (tab, navigation, index) {
            	 if(index==1){
                 	if($("#myForm").valid()){
                 		$http.put('qz/inters/modify/', $scope.inter).success(function(response){
  	           			   forward(tab, navigation, index);
  	                   });
	           	 	}else{
	           	 		return false;
	           	 	}
            	 }else if(index==2){
            		 var errorMes="";
            		 for(var i=0;i<$scope.inter_sp.bankids.length;i++){
 						if(!sp_map[$scope.inter_sp.bankids[i]]){
 							sp_map[$scope.inter_sp.bankids[i]]={};
 						}
 					 }
            		 if($scope.inter_sp != undefined && $scope.inter_sp.bankids.length>0){
            			 $.each($scope.inter_sp.bankids,function(i,bankid){
            				 var errMes="";
                			 if(sp_map[bankid] == undefined){
                				 errMes="未进行设置 ";
                			 }else{
                				 var bcode=$("#"+bankid+"_bcode").val();
                				 if(bcode.length==0){
                					 errMes="未设置渠道银行代码、"
                					 delete sp_map[bankid].code;
                				 }else{
                					 sp_map[bankid].code=bcode;
                				 }
                				 if((sp_map[bankid].code==undefined&&Object.keys(sp_map[bankid]).length==0)
                						 ||(sp_map[bankid].code!=undefined&&Object.keys(sp_map[bankid]).length==1)){
                					 errMes+="未设置支持的卡类型、";
                				 }else{
                					 $.each($scope.zfklxList,function(i,zfklx){
                    					 if(sp_map[bankid][zfklx.dictionaryId]!=undefined){
                    						 var zfklxCode=$("#"+bankid+"_"+zfklx.dictionaryId+"_zfklx").val();
                            				 if(zfklxCode.length==0){
                            					 errMes+="未设置"+zfklx.name+"代码、";
                            					 delete sp_map[bankid][zfklx.dictionaryId].code;
                            				 }else{
                            					 sp_map[bankid][zfklx.dictionaryId].code=zfklxCode;
                            				 }
                            				 sp_map[bankid][zfklx.dictionaryId].id=zfklx.dictionaryId;
                            				 var zfksx=false;
                            				 for(var key in sp_map[bankid][zfklx.dictionaryId]){
                            					 if(key != "id" && key != "code"){
                            						 zfksx=true;
                            						 break;
                            					 }
                            				 }
                            				 if(!zfksx){
                            					 errMes+="未设置"+zfklx.name+"属性、";
                            				 }
                    					 }
                    				 });
                				 }
                			 }
                			 if(errMes.length>0){
                				 errorMes+=bankMap[bankid].name+errMes.substring(0,errMes.length-1)+"<br>";
                			 }
                		 });
            		 }/**else{
            			 errorMes+="请选择支持的银行";
            		 }**/
            		 if(errorMes.length>0){
            			 $('.alert-danger').removeClass("display-none");
            			 $('.alert-danger p').html(errorMes);
            			 return false;
            		 }else{
            			 $('.alert-danger').addClass("display-none");
            			 for(var key in sp_map){
            				 if(!$scope.inter_sp.bankids.contains(key)){
            					 delete sp_map[key];
            				 }
            			 }
            			 var param={
            					 interId:$scope.inter.channelInterId,
            					 channelId:$scope.inter.channelId,
            					 spJson:JSON.stringify(sp_map)
            			 }
            			 $http.put('qz/inters/modifySpBank/', param).success(function(){
	            		 	forward(tab, navigation, index)
            			 });
            		 }
            	 }else if(index==3){
            		var deployInfo=$scope.deployInfo;
         	   		if(deployInfo!=undefined && deployInfo.length>0){
         	   			var regDeploy = /^([0|1],((?:(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))\.){3}(?:25[0-5]|2[0-4]\d|((1\d{2})|([1-9]?\d)))),([0-9]|[1-9]\d|[1-9]\d{2}|[1-9]\d{3}|[1-5]\d{4}|6[0-4]\d{3}|65[0-4]\d{2}|655[0-2]\d|6553[0-5]),(\w|-|\.|\/){0,125},(\w|-|\.|\/){0,125},(\w|-|\.|\/){0,125}\n)+$/;
	         	   		if(regDeploy.test(deployInfo+"\n")){
	            			var param={
	         	   				interId:$scope.inter.channelInterId,
	         	   				deployInfo:deployInfo
	         	   			}
	            			$http.put('qz/inters/modifyDeploy/', param).success(function(response){
	         	   				 if(response.meta.success){
	         	   					forward(tab, navigation, index)
	         	   				 }
	         	   			});
	            			$('.alert-danger').addClass("display-none");
	            		}else{
	            			$('.alert-danger').removeClass("display-none");
     	   					$('.alert-danger p').html("请检查服务器配置信息格式");
     	   					return false;
	            		}
         	   		 }else{
         	   			$('.alert-danger').removeClass("display-none");
         	   			$('.alert-danger p').html("请输入服务器配置信息");
         	   			return false;
         	   		 }
            	 }
            },
            onPrevious: function (tab, navigation, index) {
            	forward(tab, navigation, index);
            },
			onTabClick: function (tab, navigation, index) {
//                bootbox.alert('On Tab click is disabled');
				$('.alert-danger').addClass("display-none");
                return true;
            },
            onTabShow: function (tab, navigation, index) {
            	forward(tab, navigation, index);
                var total = navigation.find('li').length;
                var current = index + 1;
                var $percent = (current / total) * 100;
                $('#formWizard').find('.progress-bar').css({
                    width: $percent + '%'
                });
            }
        });

        $('#formWizard').find('.prevBtn').hide();
        $('#formWizard .submitBtn').click(function () {
        	redirectUrl("manage/inter/","list.jsp");
        }).hide();
        
	}
	$scope.initFormWizard();
	$scope.view();
	
	$scope.rmAttachTip=function(id,mes){
    	$scope.delItem={id:id,mes:mes};
    	$('#box-del').modal({
    		show: true
    	});    	
    }
    
  $scope.rmAttach=function(id){
  	$http.put('qz/inters/fileDel/'+id).success(function(response){		
			$('#box-del').modal('hide');
    	$scope.view();
    });
  }
	
  $scope.fileupload=function(){	  	
  	$.ajaxFileUpload({
      url:'qz/inters/fileUpload?interid=' + interid,
      type: 'post',
      secureuri: false, //一般设置为false
      fileElementId: 'fileid', // 上传文件的id、name属性名
      dataType: 'JSON', //返回值类型，一般设置为json、application/json 
      success: function(data, status){      	 
        //location.href='manage/inters/edit.jsp?interid=' + interid
        //$('#file_upload').replaceWith('<input type="file" name="upload" hidden="hidden" id="file_upload" accept=".zip" />'); 
        $scope.view();
      },
      error: function(data, status, e){ 
          alert(e);
      }            
      });
	}
	
//	$scope.download=function(fname){
//		$http({
//			url: 'qz/download/filedown?filename=' + fname,
//			method: "GET",
//			data: 'JSON',             
//			headers: {
//				'Content-type': 'multipart/form-data'
//			},      
//			responseType: 'arraybuffer'
//		}).success(function (data, status, headers, config) {
//		 
//			var blob = new Blob([data], {type: "applicaiton/octet-stream"});
//			var downloadUrl = window.URL.createObjectURL(blob);
//			var anchor = document.createElement("a");
//			anchor.href = downloadUrl;
//			anchor.download = fname;
//			anchor.click();
//			window.URL.revokeObjectURL(downloadUrl);
//
//		}).error(function (data, status, headers, config) {
//				console.log('Failed to download file: '+fname)
//		});	
//	}
  	/*$scope.download=function(fname){
  		document.location.href='qz/download/filedown?filename=' + fname
		$http({
			url: 'qz/download/filedown?filename=' + fname,
			method: "GET",
			data: 'JSON',             
			headers: {
				'Content-type': 'multipart/form-data'
			},      
			responseType: 'arraybuffer'
		}).success(function (data, status, headers, config) {		 
		    
		    
		    
		}).error(function (data, status, headers, config) {
			alert('error 5:'+config);
				console.log('Failed to download file: '+fname)
		});	
	}*/
	
});

Array.prototype.contains = function(obj) {
    var i = this.length;
    while (i--) {
        if (this[i] === obj) {
            return true;
        }
    }
    return false;
}

function selectedDrawing(id,mes,isValid){
	isValid=isValid==undefined?true:false;
	setTimeout(function(){
		$("#"+id).select2({
			 placeholder: mes,
			 allowClear: true
		});
		if(isValid){
			$("#"+id).change(function(){  
				$(this).valid();
			}); 
		}
	} , parseInt(Math.random() * 500));
}

function executeTimeout(fun){
	setTimeout(fun, parseInt(Math.random() * 500));
}

function executeTimeout(fun){
	setTimeout(fun, parseInt(Math.random() * 500));
}